﻿using System;
using ZHDJ.JoinParty.BLL;
using ZHDJ.Data.Models.JoinParty;
using FineUI;
using System.Data;
using ZHDJ.Core.Util;
using ZHDJ.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace JoinParty.admin.FlowStep
{
    public partial class Meeting : PageBase
    {
        public string MeetingID
        {
            get
            {
                string rID = "";
                if (!string.IsNullOrEmpty(GetQueryIntValue("MeetingID")))
                    rID = GetQueryIntValue("MeetingID");
                else
                {
                    try
                    {
                        PartyJoinLinkExample omodel = DB.PartyJoinLinkExamples.Find(this.CurrentStandID);
                        if (!string.IsNullOrEmpty(omodel.StandID))
                            rID = omodel.MeetingID;
                    }
                    catch
                    {
                        rID = "";
                    }

                }
                return rID;
            }
        }
        #region ViewPower

        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get
            {
                return "";
            }
        }

        #endregion
        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
                LoadData();
            }
        }
        private void BindData()
        {
            this.lbWorkPoint.Text = ModuleUtil.GetWorkPointConent(this.CurrentStepID);
        }

        private void LoadData(string IsSave = "")
        {
            btnClose.OnClientClick = ActiveWindow.GetHideReference();
            if (!string.IsNullOrEmpty(this.CurrentStandID))
            {
                PartyJoinLinkExample oModel = DB.PartyJoinLinkExamples.Find(this.CurrentStandID);
                PartyJoinProcess ps = DB.PartyJoinProcesss.Find(this.CurrentStepID);
                if (!string.IsNullOrEmpty(oModel.MeetingID))
                {
                    partyJoinMeeting Momdel = DB.partyJoinMeetings.Find(oModel.MeetingID);
                    this.txtMeetingTitle.Text = Momdel.Title;
                    this.txtShouldBeTo.Text = Momdel.ShouldBeTo.ToString();
                    this.txtIsTo.Text = Momdel.IsTo.ToString();
                    this.dtMeetingTime.Text = Convert.ToDateTime(Momdel.MeetingTime).ToString("yyyy-MM-dd HH:mm:ss");
                    this.heMeetingContent.Text = oModel.Remark;
                    if (string.IsNullOrEmpty(Momdel.Title))
                        this.txtMeetingTitle.Text = this.GetMettingTitle(oModel.CurrentStepID);

                }
                else
                {
                    this.dtMeetingTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    this.txtMeetingTitle.Text = this.GetMettingTitle(oModel.CurrentStepID);
                    this.btnSubmit.Visible = false;
                    this.heMeetingContent.Text = oModel.Remark;
                }
            }

            //页面只读显示
            if (this.ReadOnly.Trim() == "1")
            {
                this.btnSubmit.Visible = false;
                this.btnSaveClose.Visible = false;
            }
        }



        private void SaveData(bool isClose, bool IsSubmit = false)
        {

            string Message = "";///接收处理流程反馈的消息主要判断当前步骤是否已审核过
            bool bResult = true;
            DataSet ds = ModuleUtil.BranchLoginStantID(this.ApplyBranchID, this.CurrentStepID,this.CurrentStandID);  ///不批量处理了
            PartyJoinLinkExample oModel = null;

            var Momdel = DB.partyJoinMeetings.Find(this.MeetingID);
            if (Momdel == null)
                Momdel = new partyJoinMeeting();
            Momdel.MeetingTime = Convert.ToDateTime(this.dtMeetingTime.Text);
            Momdel.ShouldBeTo = Convert.ToInt32(this.txtShouldBeTo.Text);
            Momdel.IsTo = Convert.ToInt32(this.txtIsTo.Text);
            Momdel.Title = this.txtMeetingTitle.Text;
            Momdel.Content = this.heMeetingContent.Text;
            if (string.IsNullOrEmpty(this.MeetingID))
            {
                string errMsg = "";
                //验证会议人数是否符合规则
                if (!IsSubmitValid(ds, Momdel.ShouldBeTo, Momdel.IsTo, out errMsg, "only") && IsSubmit)
                {
                    Alert.Show(errMsg, String.Empty, ActiveWindow.GetHideReference());
                    return;
                }
                Momdel.MeetingID = StringHelper.NewID;
                DB.partyJoinMeetings.Add(Momdel);
                DB.SaveChanges();
                //Momdel.Insert();

                #region 会议和流程实例建立关系
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    oModel = DB.PartyJoinLinkExamples.Find(dr["StandID"].ToString());
                    oModel.Remark = heMeetingContent.Text;
                    //保存时更新流程实例的会议ID
                    oModel.MeetingID = Momdel.MeetingID;
                    DB.SaveChanges();
                    //oModel.Update();
                }
                #endregion
            }
            else
            {
                string errMsg = "";
                //验证会议人数是否符合规则
                if (!IsSubmitValid(ds, Momdel.ShouldBeTo, Momdel.IsTo, out errMsg) && IsSubmit)
                {
                    Alert.Show(errMsg, String.Empty, ActiveWindow.GetHideReference());
                    return;
                }
                if (!Utility.CheckFieldUnique("tblpartyjoinmeeting", "MeetingID", this.MeetingID, ""))
                {
                    DB.SaveChanges();
                }
                else
                {
                    DB.partyJoinMeetings.Add(Momdel);
                    DB.SaveChanges();
                }

                #region 会议和流程实例建立关系
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    oModel = DB.PartyJoinLinkExamples.Find(dr["StandID"].ToString());
                    //保存时更新流程实例的会议ID
                    oModel.MeetingID = Momdel.MeetingID;
                    oModel.Remark = this.heMeetingContent.Text;
                    DB.SaveChanges();
                    //oModel.Update();
                }
                #endregion

                #region 提交并生成下一步待办流程实例
                //提交时产生下一步流程
                if (IsSubmit)
                {
                    //获取上级党委ID

                    string UpBranchID = Utility.GetParentBranch(this.ApplyBranchID);

                    if (string.IsNullOrEmpty(UpBranchID))
                    {
                        UpBranchID = this.ApplyBranchID;
                    }
                    //*获取当前组织管理员/书记的ID和姓名
                    //Dictionary<string, string> dic = ModuleUtil.GetBranchAdminToDictionaryEx(this.ApplyBranchID, "");
                    string ToDoHandleUserIDs = string.Empty;
                    string ToDoHandleUserNames = string.Empty;
                    //ToDoHandleUserIDs = string.Join(",", dic.Keys.ToArray());
                    //ToDoHandleUserNames = string.Join(",", dic.Values.ToArray());
                    ToDoHandleUserIDs = UpBranchID;
                    ToDoHandleUserNames = UpBranchID;
                    //*
                    string TopBranchID = "";
                    if (this.CurrentStepID == ProcesUtil.JoinStep22)
                        TopBranchID = ModuleUtil.GetPartyAppointArray(this.ApplyBranchID);//申请的最高级审批组织ID
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        oModel = DB.PartyJoinLinkExamples.Find(dr["StandID"].ToString());
                        oModel.HandleUserID = this.CurrentUser.LoginID;
                        oModel.HandleUserName = this.CurrentUser.UserName;
                        oModel.HandleTime = DateTime.Now;
                        oModel.Status = (int)Enum_FlowStanceStatus.通过;
                        oModel.Remark = this.heMeetingContent.Text;
                        bResult = ProcesUtil.ApprovalProcesStep(oModel, out Message, TopBranchID);
                        {
                            #region 在（确认积极分子\确定发展对象）步聚产生下一步（报上级党委备案）子流程
                            if (oModel.CurrentStepID == ProcesUtil.JoinStep22)
                            {
                                PartyJoinChildFlow cFlow = new PartyJoinChildFlow();
                                cFlow.ChildFlowID = StringHelper.NewID;
                                cFlow.StandID = Convert.ToString(HttpContext.Current.Session["NextStandID"]);
                                switch (oModel.CurrentStepID)
                                {
                                    case ProcesUtil.JoinStep22: cFlow.StepID = ProcesUtil.JoinStep23; break;
                                }
                                //cFlow.StepID = oModel.CurrentStepID == ProcesUtil.JoinStep4 ? ProcesUtil.JoinStep5 : ProcesUtil.JoinStep12;
                                cFlow.ApplyBranchID = this.ApplyBranchID;
                                cFlow.ToDoBranchID = UpBranchID;//上级组织
                                cFlow.ToDoHandleUserID = ToDoHandleUserIDs;
                                cFlow.ToDoHandleUserName = ToDoHandleUserNames;
                                cFlow.Status = (int)Enum_FlowStanceStatus.未处理;
                                cFlow.OrderNo = Utility.GetSortOrderNo("tblPartyJoinChildFlow", "OrderNo", "StandID='" + cFlow.StandID + "'");
                                cFlow.CreateTime = DateTime.Now;
                                DB.PartyJoinChildFlows.Add(cFlow);
                                DB.SaveChanges();
                                HttpContext.Current.Session["NextStandID"] = null;
                            }
                            #endregion

                            if (bResult)
                            {
                                #region 更新申请人预备党员入党时间
                                if (this.CurrentStepID == ProcesUtil.JoinStep19)
                                {
                                    ModuleUtil.UpdateUserMassage(oModel.AppllicationID, "", this.dtMeetingTime.Text);
                                }
                                #endregion
                            }
                        }

                    }
                }
                #endregion
            }
            //大会会议确认积极分子人员表，如没有数据即可确认为已审批完成
            if (ds.Tables[0].Rows.Count == 0)
            {
                Alert.Show("该申请单流程已处理!", String.Empty, ActiveWindow.GetHideReference());
                return;
            }

            if (bResult)
            {
                if (IsSubmit)
                {
                    Alert.Show("提交成功!", String.Empty, ActiveWindow.GetHideReference());
                }
                else
                {
                    Alert.Show("保存成功!", String.Empty, ActiveWindow.GetHideReference());
                }
            }
            else
            {
                if (Message != "")
                {
                    Alert.Show(Message, String.Empty, ActiveWindow.GetHideReference());
                }
            }
        }
        #endregion

        #region 按钮
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            this.SaveData(true, true);
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }

        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            SaveData(false);
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }
        #endregion

        private string GetMettingTitle(string CurrentStepID)
        {
            string MeetingName = string.Empty;
            switch (CurrentStepID)
            {
                case ProcesUtil.JoinStep22: MeetingName = "支部大会讨论接收预备党员"; break;
                case ProcesUtil.JoinStep4: MeetingName = "确定积极分子"; break;
                case ProcesUtil.JoinStep24: MeetingName = "审批"; break;
                case ProcesUtil.JoinStep35: MeetingName = "支部大会讨论"; break;
                case ProcesUtil.JoinStep12: MeetingName = "确定发展对象"; break;
            }
            return MeetingName + DateTime.Now.ToString("yyyyMMdd");
        }

        /// <summary>
        /// 规则设置
        /// </summary>
        /// <param name="ds"></param>
        /// <param name="ShouldBeTo">应到人数</param>
        /// <param name="IsTo">实到人数</param>
        /// <returns></returns>
        private bool IsSubmitValid(DataSet ds, int ShouldBeTo, int IsTo, out string errMsg, string only = "")
        {
            bool isResult = true;
            errMsg = string.Empty;

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                int Agree = Convert.ToInt32(dr["Agree"]);
                int NotAgree = Convert.ToInt32(dr["NotAgree"]);
                int Waiver = Convert.ToInt32(dr["Waiver"]);
                if (!PartyJoinLinkExample.CheckRule(Agree, Waiver, NotAgree, ShouldBeTo, IsTo, out errMsg, only, "0"))
                {
                    isResult = false;
                    break;
                }
            }
            return isResult;
        }
    }
}